import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:pt_manage/dao/site_dao.dart';
import 'package:pt_manage/db/base/dao_base.dart';
import 'package:pt_manage/util/http_util.dart';
import 'package:shared_preferences/shared_preferences.dart';

import 'model/cache.dart';
import 'model/profile.dart';

class Global {
  static late SharedPreferences _prefs;
  static Profile profile = Profile();
  static List<DaoBase> dbList = [];

  static T getDb<T>() {
    return dbList.whereType<T>().first;
  }

  static void _initDB() {
    dbList.add(SiteDao());
  }

  static Future init() async {
    WidgetsFlutterBinding.ensureInitialized();
    _prefs = await SharedPreferences.getInstance();
    var cacheProfile = _prefs.getString("profile");
    if (cacheProfile != null) {
      profile = Profile.fromJson(jsonDecode(cacheProfile));
    }
    profile.cache = profile.cache ?? Cache(enable: true, expire: 3600);
    _initDB();
    HttpUtil.init();
  }

  static saveProfile() {
    _prefs.setString("profile", jsonEncode(profile.toJson()));
  }

  static void dispose() {
    if (dbList.isNotEmpty) dbList.forEach((element) async => await element.close());
  }

}